package handlers

import (
	"github.com/gin-gonic/gin"
	"picture-text-master/models"
	"strconv"
)

func CreatePicture(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")

	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "数据不能为空",
		})
		return
	}

	data := models.Picture{
		Title:   title,
		Content: content,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ListPicture(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var total int64
	models.DB.Model(&models.Picture{}).Count(&total)

	var data []models.Picture
	models.DB.Offset(offset).Limit(size).Find(&data)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  data,
		"total": total,
	})

}
